window.onload = function() {
	//元素预取
	var $canvas = document.querySelector("#canvas")
	var $btn = document.querySelectorAll("button")
	
	//画布上下文
	var ctx = $canvas.getContext("2d")
	
	//绘制形状对象
	var Sp = new Shape(ctx,"#000",$canvas.width,$canvas.height)
	
	//公共变量
	var spType = "Polygon" , mdDot , muDot , mouseDot
	
	//多边形变量
	var points = [] , flag = 0
	
	//圆变量
	var r
	
	//鼠标拖拽
	$canvas.onmousedown = function(e){
		//鼠标点击坐标
		mdDot = {x:e.x , y:e.y}
		
		//圆半径
		r = 1
		
		//路径数量
		flag++
		
		//多边形历史数据
		if(spType=="Polygon" && flag==1){
			points.push(mdDot)
		}
		
		$canvas.onmousemove = function(e) {
			mouseDot = {x:e.x , y:e.y},
			
			//绘制
			switch (spType){
				case "Circle":
					r+=2
					Sp.drawCircle(mdDot,mouseDot)
					break;
				default:
					Sp.drawPolygon(mouseDot,points,flag,muDot)
					console.log(points)	//打印多边形的所有点
					break;
			}
		}
		
		$canvas.onmouseup = function(e) {
			if(spType=="Polygon"){	
				muDot = {x:e.x , y:e.y};
				points.push(muDot)
			} 
			
			//圆历史数据缓存
			spType=="Circle" && Sp.history.push(ctx.getImageData(0, 0, $canvas.width, $canvas.height))
			
			//关闭监听
			$canvas.onmousemove = null;
			$canvas.onmouseup = null;
		}
		return false;
	}
	
	//鼠标移入高亮
	document.onmousemove = function(e) {
		//绘制
		if(ctx.isPointInPath(e.x,e.y)) {
			ctx.strokeStyle = "#f00"
			// ctx.fillStyle = "#f00"
		} else {
			ctx.strokeStyle = "#000"
			// ctx.fillStyle = "#000"
		}
		ctx.stroke()
		// ctx.fill()
	}
	
	
	//按钮切换
	for (var i = 0; i < $btn.length; i++) {
		$btn[i].onclick = function(e){
			document.querySelector(".act").className = ""
			e.srcElement.className = "act"
			//改变形状
			spType = document.querySelector(".act").id
			//切换形状时保存历史数据
			Sp.history.push(ctx.getImageData(0, 0, $canvas.width, $canvas.height))
			//切换形状时置空多边形数据
			points = []
			flag = 0
		}
	}
}